package com.atguigu.crowd.handler;

import com.atguigu.crowd.api.MySQLRemoteService;
import com.atguigu.crowd.config.OSSProperties;
import com.atguigu.crowd.constant.CrowdConstant;
import com.atguigu.crowd.entity.vo.*;
import com.atguigu.crowd.util.ResultEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import static com.atguigu.crowd.util.CrowdUtil.uploadFileToOss;

@Controller
public class ProjectConsumerHandler {

    @Autowired
    private OSSProperties ossProperties;

    @Autowired
    private MySQLRemoteService mySQLRemoteService;


    @RequestMapping("show/project/detail/{projectId}")
    public String getProjectDetail(@PathVariable("projectId") Integer projectId, ModelMap modelMap) {

        ResultEntity<DetailProjectVO> detailProjectVORemote = mySQLRemoteService.getDetailProjectVORemote(projectId);

        if (ResultEntity.SUCCESS.equals(detailProjectVORemote.getResult())) {
            DetailProjectVO data = detailProjectVORemote.getData();
            modelMap.put("detailProjectVO", data);
        }

        return "project-show-detail";
    }


    @RequestMapping("/create/confirm.html")
    public String saveConfirm(ModelMap modelMap, HttpSession session, MemberConfirmInfoVO memberConfirmInfoVO) {

        //1、从session域读取之前临时存储的ProjectVO对象
        ProjectVO projectVO = (ProjectVO) session.getAttribute(CrowdConstant.ATTR_NAME_TEMPLE_PROJECT);

        //2、如果ProjectVO对象为null
        if (projectVO == null) {
            throw new RuntimeException(CrowdConstant.MESSAGE_TEMPLE_PROJECT_MISSING);
        }

        //3、将确认信息设置到ProjectVO对象中
        projectVO.setMemberConfirmInfoVO(memberConfirmInfoVO);

        //4、从session域读取当前登录的用户
        MemberLoginVO memberLoginVO = (MemberLoginVO) session.getAttribute(CrowdConstant.ATTR_NAME_LOGIN_MEMBER);
        Integer memberId = memberLoginVO.getId();

        //5、调用远程方法保存projectVo对象
        ResultEntity<String> saveResultEntity = mySQLRemoteService.saveProjectVORemote(projectVO, memberId);

        //6、判断远程的保存操作是否成功
        String result = saveResultEntity.getResult();
        if (ResultEntity.FAILED.equals(result)) {
            modelMap.addAttribute(CrowdConstant.ATTR_NAME_MESSAGE, saveResultEntity.getMessage());
            return "project-confirm";
        }

        //7、将临时的ProjectVO对象从Session域移除
        session.removeAttribute(CrowdConstant.ATTR_NAME_TEMPLE_PROJECT);

        return "redirect:http://localhost/project/create/success.html";
    }


    @ResponseBody
    @RequestMapping("/create/save/return.json")
    public ResultEntity<String> saveReturn(ReturnVO returnVO, HttpSession session) {

        try {
            //1、从session域中读取之前缓存的ProjectVO对象
            ProjectVO projectVo = (ProjectVO) session.getAttribute(CrowdConstant.ATTR_NAME_TEMPLE_PROJECT);

            //2、判断projectvo是否为null
            if (projectVo == null) {
                return ResultEntity.failed(CrowdConstant.MESSAGE_TEMPLE_PROJECT_MISSING);
            }

            //3、从projectVO对象中获取存储回报信息的集合
            List<ReturnVO> returnVOList = projectVo.getReturnVOList();

            //4、判断returnVOList集合是否有效
            if (returnVOList == null || returnVOList.size() == 0) {
                //5、创建集合对象对returnVolist进行初始化
                returnVOList = new ArrayList<>();
                //6、为了让以后能够正常使用这个集合，设置到projectVo对象中
                projectVo.setReturnVOList(returnVOList);
            }

            //7、将收集了表单数据的returnVO对象存入集合
            returnVOList.add(returnVO);

            //8、把数据有变化的ProjectVO对象重新存入Session域，以确保新的数据最终能够存入Redis
            session.setAttribute(CrowdConstant.ATTR_NAME_TEMPLE_PROJECT, projectVo);

            //所有操作成功完成，返回成功
            return ResultEntity.successWithoutData();
        } catch (Exception exception) {
            exception.printStackTrace();
            return ResultEntity.failed(exception.getMessage());
        }

    }


    /**
     * returnPicture是请求参数的名字
     * file是请求参数的值，也就是要上传的文件
     *
     * @param returnPicture
     * @return
     */
    @ResponseBody
    @RequestMapping("/create/upload/return/picture.json")
    public ResultEntity<String> uploadReturnPicture(@RequestParam("returnPicture") MultipartFile returnPicture) throws IOException {

        //1、执行文件上传
        ResultEntity<String> uploadReturnPictureFileToOss = uploadFileToOss(
                ossProperties.getEndPoint(),
                ossProperties.getAccessKeyId(),
                ossProperties.getAccessKeySecret(),
                ossProperties.getBucketName(),
                ossProperties.getBucketDomain(),
                returnPicture.getInputStream(),
                returnPicture.getOriginalFilename());

        //返回上传的结果
        return uploadReturnPictureFileToOss;
    }


    @RequestMapping("/create/project/information")
    public String saveProjectBasicInfo(
            //接收除了上传图片之外的其他普通数据
            ProjectVO projectVO,
            MultipartFile headerPicture,
            List<MultipartFile> detailPictureList,
            HttpSession session,
            ModelMap modelMap) throws IOException {

        //1、完成头图上传
        boolean empty = headerPicture.isEmpty();
        if (!empty) {
            //如果用户确实上传了有内容的文件，则执行上传
            ResultEntity<String> uploadHeaderPictureFileToOss = uploadFileToOss(
                    ossProperties.getEndPoint(),
                    ossProperties.getAccessKeyId(),
                    ossProperties.getAccessKeySecret(),
                    ossProperties.getBucketName(),
                    ossProperties.getBucketDomain(),
                    headerPicture.getInputStream(),
                    headerPicture.getOriginalFilename());

            String result = uploadHeaderPictureFileToOss.getResult();
            //3、判断头图是否上传成功
            if (ResultEntity.SUCCESS.equals(result)) {
                //4、从返回的数据中获取图片访问地址
                String headerPicturePath = uploadHeaderPictureFileToOss.getData();

                // 5、存入ProjectVo对象中
                projectVO.setHeaderPicturePath(headerPicturePath);
            } else {
                modelMap.addAttribute(CrowdConstant.ATTR_NAME_MESSAGE, CrowdConstant.MESSAGE_HEADER_PIC_UPLOAD_FAILED);

                return "project-launch";
            }
        }

        // 4、遍历detailPictureList集合

        //创建一个用来存放详情图片路径的集合
        List<String> detailPicturePathList = new ArrayList<>();

        for (MultipartFile detailPicture : detailPictureList) {
            //5、当前detailPicture是否为空
            if (!detailPicture.isEmpty()) {
                //6、执行上传
                ResultEntity<String> uploadDetailPictureFileToOss = uploadFileToOss(
                        ossProperties.getEndPoint(),
                        ossProperties.getAccessKeyId(),
                        ossProperties.getAccessKeySecret(),
                        ossProperties.getBucketName(),
                        ossProperties.getBucketDomain(),
                        detailPicture.getInputStream(),
                        detailPicture.getOriginalFilename());

                String result = uploadDetailPictureFileToOss.getResult();
                //7、是否上传成功
                if (ResultEntity.SUCCESS.equals(result)) {
                    //8、从返回的数据中获取图片访问地址
                    String detailPicturePath = uploadDetailPictureFileToOss.getData();

                    // 存入detailPicturePathList集合中
                    detailPicturePathList.add(detailPicturePath);
                }
            }

        }
        //9、detailPicturePathList集合放入ProjectVO中
        projectVO.setDetailPicturePathList(detailPicturePathList);


        //10、将ProjectVO对象存入Session域中
        session.setAttribute(CrowdConstant.ATTR_NAME_TEMPLE_PROJECT, projectVO);


        //已完整的访问路径前往下一个收集回报信息的页面
        return "redirect:http://localhost/project/return/info/page.html";
    }

}
